package com.dhcc.controller;

import com.dhcc.api.R;
import com.dhcc.dto.ClientUserDto;
import com.dhcc.dto.UserDto;
import com.dhcc.entity.ClientUser;
import com.dhcc.entity.ClientUserDepartmentPositionInstitution;
import com.dhcc.entity.SysDepartment;
import com.dhcc.entity.SysUserPosition;
import com.dhcc.httpApiService.IdGeneratorService;
import com.dhcc.service.*;
import com.dhcc.utils.AuthUtil;
import com.dhcc.vo.ClientUserInfo;
import com.dhcc.vo.SysUserVO;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/userSystem/user")
public class UserController {
    @Resource
    private SysUsersService sysUsersService;
    @Resource
    private SysUserDepartmentInstitutionService sysUserDepartmentInstitutionService;
    @Resource
    private SysUserOrganizationService sysUserOrganizationService;
    @Resource
    private ClientUserService clientUserService;
    @Resource
    private ClientUserDepartmentPositionInstitutionService clientUserDepartmentPositionInstitutionService;
    @Resource
    private IdGeneratorService idGeneratorService;
    @Resource
    private SysDepartmentService sysDepartmentService;
    @Resource
    private SysUserPositionService sysUserPositionService;
    /**
     * 变更管理员
     */
    @PostMapping("/changeAdmin/user")
    public R changeAdmin(UserDto userDto,UserDto changeUser){
        Integer changge=sysUserDepartmentInstitutionService.updateUserPositionByUserId(userDto.getUserId(),userDto.getPositionId());
        Integer integer = sysUserDepartmentInstitutionService.updateUserPositionByUserId(changeUser.getUserId(), changeUser.getPositionId());
        if (integer!=0&&changge!=0){
           return R.success();
        }else {
            return R.fail("变更失败");
        }
    }
    /**
     * 查询当前机构下的用户列表
     */
    @GetMapping("/selectUserListByInstitutionId")
    public R<List<SysUserVO>> selectUserListByInstitutionId(String institutionId){
        //通过用户与机构关联表查询当前机构下的所有用户编号
        List<String> userIds=sysUserOrganizationService.getUserIdsByInstitutionId(institutionId);
        List<SysUserVO> userVOList=new ArrayList<>();
        //便利用户id集合查询每个用户id对应的用户信息
        for (String userId : userIds) {
            //通过用户id查询用户信息
            ClientUser user = clientUserService.getUserById(userId);
            //复制数据
            SysUserVO sysUserVO=new SysUserVO();
            BeanUtils.copyProperties(user,sysUserVO);
            //通过用户编号和机构编号查询部门编号和岗位编号
            ClientUserDepartmentPositionInstitution clientUserDepartmentPositionInstitution=clientUserDepartmentPositionInstitutionService.getDepartmentIdAndPoaitionId(userId,institutionId);
            sysUserVO.setDepartmentId(clientUserDepartmentPositionInstitution.getDepartmentId());
            //通过部门编号查询部门名称
            SysDepartment depatment = sysDepartmentService.getDepatment(clientUserDepartmentPositionInstitution.getDepartmentId());
            sysUserVO.setDepartmentName(depatment.getDeptName());
            sysUserVO.setPositionId(clientUserDepartmentPositionInstitution.getPositionId());
            //通过岗位编号查询岗位名称
            SysUserPosition positionName = sysUserPositionService.getPositionName(clientUserDepartmentPositionInstitution.getPositionId());
            sysUserVO.setPositionName(positionName.getPositionName());
            sysUserVO.setInstitutionId(institutionId);
            userVOList.add(sysUserVO);
        }
        return R.data(userVOList);
    }
    /**
     * 在当前机构下添加新的用户
     */
    @PostMapping("/addUserByInstitutionId")
    public R addUserByInstitutionId(@RequestBody ClientUserDto clientUserDto){
        clientUserDto.setUserId(idGeneratorService.nextId().toString());
        ClientUser clientUser=new ClientUser();
        BeanUtils.copyProperties(clientUserDto,clientUser);
        Integer addUserResult = clientUserService.addUser(clientUser);
        if (addUserResult==0){
            throw new RuntimeException("用户添加异常");
        }
        //在用户，机构关联表中添加对应的数据
        Integer addResult=sysUserOrganizationService.add(clientUser.getUserId(),clientUserDto.getInstitutionId());
        if (addResult==0){
            throw new RuntimeException("用户，机构关联表数据添加异常");
        }
        //在用户，机构,部门，岗位关联表中添加对应的数据
        Integer result= clientUserDepartmentPositionInstitutionService.add(clientUser.getUserId(),clientUserDto.getInstitutionId(),clientUserDto.getDepartmentId(),clientUserDto.getPositionId());
        if (result==0){
            throw new RuntimeException("用户，机构,部门，岗位关联表数据添加异常");
        }
        return R.success();
    }
    /**
     * 删除当前机构下的用户
     */
    @GetMapping("/deleteUserByUserId")
    @Transactional
    public R deleteUserByUserId(String userId,String institutionId){
        //删除用户与机构关联表中对应的数据
        Integer result=sysUserOrganizationService.deleteByUserIdAndInstitutionId(userId,institutionId);
        if (result==0){
            throw new RuntimeException("用户与机构关联表删除异常");
        }
        return R.success();
    }
    /**
     * 修改用户信息
     */
    @PostMapping("/updateUserByUserId")
    @Transactional
    public R updateUserByUserId(@RequestBody ClientUserInfo clientUserInfo){
        ClientUser clientUser=new ClientUserInfo();
        BeanUtils.copyProperties(clientUserInfo,clientUser);
        //判断需要修改的用户是否为当前登录用户
        if (clientUser.getUserId().toString().equals(AuthUtil.getUserId())){
            //修改用户信息
            Integer update=clientUserService.updateUser(clientUser);
            if (update==0){
                throw new RuntimeException("修改用户表数据出现异常");
            }
            //修改用户,机构,部门，岗位关联表中的信息
            Integer updateResult= clientUserDepartmentPositionInstitutionService.updateDepartmentAndPosition(clientUserInfo.getUserId(),clientUserInfo.getInstitutionId(),clientUserInfo.getDepartmentId(),clientUserInfo.getPositionId());
            if (updateResult==0){
                throw new RuntimeException("修改用户,机构,部门，岗位关联表数据出现异常");
            }
            return R.success();
        }else {
            throw new RuntimeException("当前登录用户必须与要修改的用户一致");
        }
    }
    /**
     * 查询用户详情
     */
    @GetMapping("selectUserByUserIdAndInstitutionId")
    public R<ClientUserInfo>  selectUserByUserIdAndInstitutionId(String userId,String institutionId,String institutionRoleId){
        ClientUserInfo clientUserInfo=clientUserService.selectUserByUserIdAndInstitutionId(userId,institutionId,institutionRoleId);
        return R.data(clientUserInfo);
    }

}
